import { Upload } from 'antd';
import { useState, useEffect } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';

function UpPhoto({ onButtonClick, picture }: any): JSX.Element {

	//获取token值
	let token: any = sessionStorage.getItem('token')

	const getBase64 = (img: RcFile, callback: (url: string) => void) => {
		const reader = new FileReader();
		reader.addEventListener('load', () => callback(reader.result as string));
		reader.readAsDataURL(img);
	};

	const [loading, setLoading] = useState(false);
	const [imageUrl, setImageUrl] = useState<string>();
	
	let picturet = process.env.REACT_APP_IMG_URL + picture

	useEffect(() => {
		console.log(picture);

		if (picture != undefined) {
			setImageUrl(picturet)
		}
	}, [])
	//点击上传图片
	const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
		//上传中
		if (info.file.status === 'uploading') {
			setLoading(true);
			return;
		}
		//上传完毕
		if (info.file.status === 'done') {
			// Get this url from response in real world.
			getBase64(info.file.originFileObj as RcFile, (url) => {
				setLoading(false);
				setImageUrl(url);
			});

			// console.log(11111,info.file.response.data);
			
			//如果上传成功
			if (info.fileList) {
				info.fileList.forEach((item: any) => {
					console.log('123', item.response.data);
					//子传父
					onButtonClick(item.response.data)
				})
			}
		}
	};

	const uploadButton = (
		<div>
			{loading ? <LoadingOutlined /> : <PlusOutlined />}
			<div style={{ marginTop: 8 }}>Upload</div>
		</div>
	);

	return (
		<div>
			<Upload
				name="file"
				listType="picture-card"
				className="avatar-uploader"
				showUploadList={false}
				action='http://estate.eshareedu.cn/estate/api/upload/add'
				onChange={handleChange}
				headers={{ 'Authorization': token }}
			>
				{imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '50%' }} /> : uploadButton}
			</Upload>
		</div>
	);
}

export default UpPhoto;